import com.sun.net.httpserver.*;

import java.io.*;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;

//接送接口服务端
public class HttpServerExample {
    public static void main(String[] args) throws IOException {
        // 1. 创建HTTP服务器
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);

        // 2. 创建上下文处理器
        server.createContext("/api/push", new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                try {
                    // 2.1 只处理POST请求
                    if (!"POST".equalsIgnoreCase(exchange.getRequestMethod())) {
                        sendResponse(exchange, 405, "Method Not Allowed");
                        return;
                    }

                    // 2.2 验证Token
                    String authHeader = exchange.getRequestHeaders().getFirst("Authorization");
                    if (authHeader == null || !authHeader.equals("Bearer test123")) {
                        sendResponse(exchange, 401, "Unauthorized");
                        return;
                    }

                    // 2.3 读取请求体（JDK8兼容写法）
                    InputStream is = exchange.getRequestBody();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = is.read(buffer)) != -1) {
                        bos.write(buffer, 0, len);
                    }
                    String requestBody = new String(bos.toByteArray(), StandardCharsets.UTF_8);

                    System.out.println("收到请求: " + requestBody);

                    // 2.4 返回响应
                    String response = "{\"status\":\"success\",\"code\":200}";
                    sendResponse(exchange, 200, response);

                } catch (Exception e) {
                    e.printStackTrace();
                    sendResponse(exchange, 500, "Internal Server Error");
                }
            }
        });

        // 3. 设置线程池并启动服务
        server.setExecutor(Executors.newFixedThreadPool(10));
        server.start();
        System.out.println("服务器已启动，监听端口: 8080");
    }

    private static void sendResponse(HttpExchange exchange, int statusCode, String response) throws IOException {
        exchange.getResponseHeaders().set("Content-Type", "application/json");
        exchange.sendResponseHeaders(statusCode, response.length());
        try (OutputStream os = exchange.getResponseBody()) {
            os.write(response.getBytes(StandardCharsets.UTF_8));
        }
    }
}